package com.steak.concurrent.lock.reentrantwriteandreadlock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 刘牌
 * @Title:
 * @date 2022/2/2314:08
 */
public class ThreadSafeReadWriteArrayList<T> {

    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    private final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
    private final List<T> list = new ArrayList<>();

    public boolean add(T t){
        writeLock.lock();
        try {
            return list.add(t);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            writeLock.unlock();
        }
    }

    public boolean remove(T t){
        writeLock.lock();
        try {
            return list.remove(t);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            writeLock.unlock();
        }
    }

    public T get(int index){
        readLock.lock();
        try {
            return list.get(index);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            readLock.unlock();
        }
    }
}
